package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.commom.exception.CustException;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.pojo.WmNewsMaterial;
import com.heima.model.wemedia.pojo.WmMaterial;
import com.heima.model.wemedia.pojo.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
 * @author by jojo
 * @Date 2022/3/1
 * @Description
 */
@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Value("${file.oss.prefix}")
    private String prefix;
    @Value("${file.oss.web-site}")
    private String webSite;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //参数校验
        if (multipartFile == null || multipartFile.getSize() == 0) {
            log.error("文件参数错误 {}", multipartFile);
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文件参数错误");
        }
        //检查token中的参数是否存在
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser == null) {
            log.error("登录之后才可以上传素材");
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "登录之后才可以上传素材");
        }
        //检查文件后缀
        //获取原始文件名称
        String originalFilename = multipartFile.getOriginalFilename();
        if (originalFilename == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "图片不存在");
        }
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //判断文件后缀是否符合
        boolean flag= checkSuffix(suffix);
        if (!flag) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文件类型不支持...");
        }
        //上传0SS
        String fileUrl = UUID.randomUUID().toString().replace("-", "");
        try {
            fileUrl = fileStorageService.store(prefix, fileUrl + suffix, multipartFile.getInputStream());
            log.info("阿里云上传图片成功 {}",fileUrl);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("阿里云上传图片失败 {}",e);
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "服务器繁忙，请稍后再试...");
        }
        //封装数据保存到素材库
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setIsCollection(WemediaConstants.WMMATERIAL_ISCOLLECTION);
        wmMaterial.setType(WemediaConstants.WMMATERIAL_TYPE);
        wmMaterial.setUserId(wmUser.getId());
        wmMaterial.setUrl(fileUrl);
        wmMaterial.setCreatedTime(new Date());
        this.save(wmMaterial);
        //响应数据
        wmMaterial.setUrl(webSite+fileUrl);
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult pageList(WmMaterialDTO dto) {
        //校验参数
        dto.checkParam();
        //封装参数
        Page<WmMaterial> page = new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.lambdaQuery();
        if (dto.getIsCollection()!=null&& WemediaConstants.WMMATERIAL_NEW_ISCOLLECTION.equals(dto.getIsCollection())) {
            wrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //获取当前登录用户
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser==null) {
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH,"请先登录...");
        }
        //比较用户id
        wrapper.eq(WmMaterial::getUserId,wmUser.getId());
        //时间倒序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        IPage<WmMaterial> iPage = this.page(page, wrapper);
        //封装数据返回
        List<WmMaterial> records = iPage.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(webSite+record.getUrl());
        }
        return new PageResponseResult(dto.getPage(),dto.getSize(),iPage.getTotal(),records);
    }

    @Override
    public ResponseResult delPicture(Integer id) {
        //校验参数
        if (id==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"id不能为空");
        }
        //用id查数据库，看是否有该素材
        WmMaterial wmMaterial = this.getById(id);
        if (wmMaterial==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"该id对应的素材不存在");
        }
        //判断图片是否被引用
        LambdaQueryWrapper<WmNewsMaterial> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(WmNewsMaterial::getMaterialId,wmMaterial.getId());
        Integer count = wmNewsMaterialMapper.selectCount(wrapper);
        if (count>0){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"该素材被引用，无法删除");
        }
        //删除数据库素材
        this.removeById(id);
        //删除OSS
        fileStorageService.delete(wmMaterial.getUrl());
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //校验参数
        if (id==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"ID不能为空");
        }
        //使用id查数据库
        WmMaterial wmMaterial = this.getById(id);
        if (wmMaterial==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Integer apUserId = WmThreadLocalUtils.getUser().getId();
        if (!apUserId.equals(wmMaterial.getUserId())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"只能收藏自己上传的素材");
        }
        wmMaterial.setIsCollection(type);
        this.updateById(wmMaterial);
        return ResponseResult.okResult();
    }

    private boolean checkSuffix(String suffix) {
        if (StringUtils.isBlank(suffix)) {
            return false;
        }
        List<String > list = Arrays.asList(".jpg",".jpeg",".webp",".png",".gif");
        for (String allowSuffix : list) {
            if (allowSuffix.equals(suffix)) {
                return true;
            }
        }
        return false;
    }
}
